//数字车间
import WorkShop from '@/router/modules/workshop'
//系统设置
import SystemSet from '@/router/modules/systemSet'
// 知识图库
import KonwledgeGraph from '@/router/modules/konwledgeGraph'

// 设备管理
import EquipManage from '@/router/modules/equipManage'

// 数据挖掘
import DataMining from '@/router/modules/dataMining'

//虚拟化
import Visualization from '@/router/modules/visualization'

// 车间模拟
import WSsimulation from '@/router/modules/wssimulation'

import MenuApi from '@/api/menuApi'

import { asyncRoutes } from '@/router/index'
import router from './router'
import store from './store'
import Encrypt from '@/common/utils/encrypt'
import Vue from 'vue'
import '@/common/plugins/element.js'


// 路由list
const routerList = []
// 路由编号
const routerNum = []

// redirect路由
var redirectRouter = 'null'

/**
 * to表示即将进入的页面路由，
 * from表示当前导航正要离开的路由
 * next: Function:执行效果依赖 next 方法的调用参数。
 * next(): 进行管道中的下一个钩子。如果全部钩子执行完了，则导航的状态就是 confirmed （确认的）。
 * next(false): 中断当前的导航。如果浏览器的 URL 改变了（可能是用户手动或者浏览器后退按钮），那么 URL 地址会重置到 from 路由对应的地址。
 * next('/') 或者 next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断，然后进行一个新的导航。
 * next(error): (2.4.0+) 如果传入 next 的参数是一个 Error 实例，则导航会被终止且该错误会被传递给 router.onError() 注册过的回调。
*/
router.beforeEach((to, from, next) => {
  /* 路由发生变化修改页面title */
  if (to.meta.title) { // 路由发生变化修改页面title
      document.title = to.meta.title
  }

  // if(to.path === '/login'){
  //   next()
  // }else{
    // console.log(store.state.RouterList)
    if (true) {
      var isLogin = localStorage.getItem("utoken")  ?  localStorage.getItem("utoken") : ''
      if (isLogin.length > 0) {
        redirectRouter = to.path
        if(to.path != "/login"){
          next()
        }else{
          localStorage.clear("utoken")
          localStorage.clear("authorization_name")
          localStorage.clear("uname")
          localStorage.clear("activeIndex")
          sessionStorage.clear("routerList")
          next()
        }
      } else {
        if(to.path === "/login" || to.path === "/"){
          next()
        }else{
          redirectRouter = to.path
          next({
            path: '/login',
            query: { redirect: to.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
          })
        }
      }
    } else {
        next()
    }
  // }
})


// 获取路由
export function toRouter(){
  // 判断是否存在路由
  var existRoute = sessionStorage.getItem("routerList") ? true:false
  // 获取当前路由
  if(existRoute){
    getRouterFormSession(redirectRouter)
  }else{
    getRouterFormApi(redirectRouter)
  }
}


/**
 * 通过缓存获取router
 */
export function getRouterFormSession(redirectRouter){
  var routenumList = Encrypt.decryptCBC(sessionStorage.getItem("routerList"))
  var list = routenumList.split(',')
  list.map(val =>{
    if(val === "10000"){
      routerList.push(WorkShop)
    }else if(val === "20000"){
      routerList.push(KonwledgeGraph)
    }else if(val === "30000"){
      routerList.push(EquipManage)
    }else if(val === "40000"){
      routerList.push(DataMining)
    }else if(val === "50000"){
      routerList.push(Visualization)
    }else{
      routerList.push(SystemSet)
    }
  })
  router.addRoutes(routerList)
  router.push({
    path:redirectRouter
  }).catch(err => {err})
}

/**
 * 通过缓存获取router 已经登陆再次进入登陆页面
 */
export function loginAginFormSession(){
  var routenumList = Encrypt.decryptCBC(sessionStorage.getItem("routerList"))
  var list = routenumList.split(',')
  list.map(val =>{
    if(val === "10000"){
      routerList.push(WorkShop)
    }else if(val === "20000"){
      routerList.push(KonwledgeGraph)
    }else if(val === "30000"){
      routerList.push(EquipManage)
    }else if(val === "40000"){
      routerList.push(DataMining)
    }else if(val === "50000"){
      routerList.push(Visualization)
    }else{
      routerList.push(SystemSet)
    }
  })
  router.addRoutes(routerList)
  alert(routerList[0].path)
  router.push({
    path:routerList[0].path
  }).catch(err => {err})
}

/**
 * 通过Api获取router
 */
export function getRouterFormApi(redirectRouter){
  // alert("api")
  MenuApi.menuList().then(res => {
    if(res.data.status === "200"){
      res.data.data.children.map(val => {
        if(val.t.menuId === "10000"){
          routerList.push(WorkShop)
          routerNum.push(10000)
        }else if(val.t.menuId === "20000"){
          routerList.push(KonwledgeGraph)
          routerNum.push(20000)
        }else if(val.t.menuId === "30000"){
          routerList.push(EquipManage)
          routerNum.push(30000)
        }else if(val.t.menuId === "40000"){
          routerList.push(DataMining)
          routerNum.push(40000)
        }else if(val.t.menuId === "50000"){
          routerList.push(Visualization)
          routerNum.push(50000)
        }else{
          routerList.push(SystemSet)
          routerNum.push(60000)
        }
      })
      router.addRoutes(routerList)
      // 将这个路由加密存入sessionStorage
      sessionStorage.setItem("routerList",Encrypt.encryptCBC(routerNum.join(',')))
      // alert(redirectRouter)
      if(redirectRouter === 'null'|| redirectRouter === '/login'){
        router.push({
          path:routerList[0].path
        }).catch(err => {err})
      }else{
        router.push({
          path:redirectRouter
        }).catch(err => {err})
      }
    }
  })
}
